package com.hziee.graduate.ticket.common;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hziee.graduate.ticket.dao.OrderDao;
import com.hziee.graduate.ticket.entity.Order;
import com.hziee.graduate.ticket.service.OrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

@Component
public class ScheduleTask {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderDao orderDao;

    protected static Logger log= (Logger) Logger.getLogger(String.valueOf(ScheduledTask.class));

    @Scheduled(cron = "0 0/5 * * * ?") //每5分钟执行一次
    @Transactional
    public void scheduledTaskByCorn() {
        //这里是对某个代码段或者某个功能进行定时操作
        // 查询每个订单，定期取消
        List<Order> orders = orderDao.selectList(new QueryWrapper<Order>());
        orders.forEach(item -> {
            // 如果创建时间加5分粥还是小于现在的时间，那么说明该订单是5分钟之前的
            if (item.getCreateTime().plusMinutes(5).isBefore(LocalDateTime.now())) {
                orderService.cancelOrder(item.getOrderId());
            }
        });
        //输出时间
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        log.info("定时任务："+date);
    }

}

